var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.SHOP09;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'shop/gift/list';
var DIALOG = {
	commonDialog:function(id,url){
		$.dialog({ 
		   	id:id,
		   	title:false,
		   	max: false,
		   	min: false,
		   	cache : false,
		   	fixed:false,
		   	drag:false,
		   	resize:false,
		   	lock:false,
		   	content:'url:'+url
	    }).max();
	}
};
var Utils = {
	doModify:function(gi_id){
		var id="modify";
		var url = config.BASEPATH+"shop/gift/to_update?gi_id="+gi_id;
		if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
			return ;
		};
		DIALOG.commonDialog(id,url);
	},
	doOpenDetail:function(lg_id){
		var id="openDetail";
		var rowData = $("#grid").jqGrid("getRowData", lg_id);
		var url = config.BASEPATH+"line/lineGiftDetail.action";
		url += '?LG_Id='+lg_id;
		url += '&pi_no='+rowData.lg_pi_no;
		url += '&si_code='+rowData.lg_si_code;
		DIALOG.commonDialog(id,url);
	},
	viewgiftrun:function(gi_pd_code,gi_shop_code){
		var id = 'viewGiftRun';
		var params = "gi_pd_code="+gi_pd_code+"&gi_shop_code="+gi_shop_code;
		var url = config.BASEPATH+"shop/gift/to_run_list?"+params;
		DIALOG.commonDialog(id,url);
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#gi_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	}
};


var handle = {
	//修改、新增
	operate: function(oper, rowId){
		 var url="";
		if(oper == 'add'){
			url = config.BASEPATH+"shop/gift/to_add";
		}else if(oper == 'edit'){
			url = config.BASEPATH+"shop/gift/to_update?gi_id="+rowId;
		}
		$.dialog({
			title : false,
			max : false,
			min : false,
			cache : false,
			lock:false,
			content:'url:'+url
		   	}).max();
	},
	del: function(rowId,pd_code,shop_code){
		$.dialog.confirm('数据删除后无法恢复，确定要删除吗？', function(){
		    $.ajax({
				type:"POST",
				url:config.BASEPATH+"shop/gift/del",
				data:"gi_id="+rowId+"&pd_code="+pd_code+"&shop_code="+shop_code,
				cache:false,
				dataType:"json",
				success:function(data){
				 	if(undefined != data && data.stat == 200){
					  	Public.tips({type: 3, content : '数据删除成功!'});
					  	$('#grid').jqGrid('delRowData', rowId);
					}else{
						Public.tips({type: 1, content : '删除失败,请联系管理员!'});
					}
				}
			 });
		}, function(){
		   return;
		});	
    },
	callback: function(data, oper, dialogWin){
		var gridData = $("#grid").data('gridData');
		if(!gridData){
			gridData = {};
			$("#grid").data('gridData', gridData);
		}
		gridData[data.id] = data;
	},
	stateFmatter:function(val,opt,row){
		var _name = "下架";
		if(row.gi_state != 1){
			_name = "上架";
		}
		return _name;
	},
	lastAmountFmatter:function(val,opt,row){
		var _val = row.totalamount - row.getamount;
		return _val;
	},
	addImage: function(pd_code){//新增图片
		if(pd_code != undefined && pd_code != ''){
			$.dialog({ 
				id: 'id',
				title: '商品图片',
				max: false,
				min: false,
				width: '830px',
				height: '400px',
				fixed:false,
				drag: true,
				content:'url:'+config.BASEPATH+'base/product/to_img_add?pd_code='+pd_code
			});
		}else{
			Public.tips({type: 1, content : '数据出错，请联系管理员!!!'});
		}
    },
	//上架下架操作 
    showGift:function(pd_code,shop_code,state){
    	$.dialog.confirm('确定进行该操作吗？', function(){  
    		$.ajax({
    			type:"POST",
    			url:config.BASEPATH+"shop/gift/show_gift",
    			data:"pd_code="+pd_code+"&shop_code="+shop_code+"&state="+state,
    			cache:false,
    			dataType:"json",
    			success:function(data){
    				if(undefined != data && data.stat == 200){
    					if(state=='0'){
    						Public.tips({type: 2, content : '礼品成功上架，会员将可以兑换！'});
    					}else if(state=='1'){
    						Public.tips({type: 2, content : '礼品已下架，会员将无法兑换！'});
    					}
    					THISPAGE.reloadData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
    			}
    		});	
    		}, function(){
    	   return;
    	}); 
    }
};
		
var format = {
	money: function(val,opt,row){
		var val = Public.numToCurrency(val);
		return val || '&#160;';
	},
	quantity: function(val,opt,row){
		return val || '&#160;';
	}
};
  
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $('#date');
	 	this.$_date.cssRadio(
		 	{callback:
		 		function($_obj){  //$_obj是radio外面的lable
		 			dateRedioClick($_obj.find("input").attr("id"));
		 		}
		 	}
	 	);
	 	this.$_satae = $('#satae');
	 	this.$_satae.cssRadio(
		 	{callback:
		 		function($_obj){  //$_obj是radio外面的lable
		 			$("#gi_state").val($($_obj).find('input').val());
		 		}
		 	}
	 	);
	},
	gridTotal:function(){
		var grid=$('#grid');
		var totalamount=grid.getCol('totalamount',false,'sum');
    	var getamount=grid.getCol('getamount',false,'sum');
    	var lastamount=grid.getCol('lastamount',false,'sum');
    	grid.footerData('set',{totalamount:totalamount,getamount:getamount,lastamount:lastamount});	
    },
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
			{label:'操作',name: 'operate', width:100, fixed:true,  title: false,sortable:false,align:'center'},
			{label:'发放店铺',name: 'sp_name', index: 'sp_name', width: 140, title: false},
			{label:'礼品货号',name: 'pd_no', index: 'pd_no', width: 100, title: false,fixed:true},
	    	{label:'礼品名称',name: 'pd_name', index: 'pd_name', width: 140, title: false},
	    	{label:'礼品状态',name: 'gi_state', index: 'gi_state', width:80, title: false,align:'center',formatter:handle.stateFmatter,},
	    	{label:'发布数量',name: 'totalamount', index: 'totalamount', width: 70, title: false,align:'right'},
	    	{label:'已兑换数量',name: 'getamount', index: 'getamount', width: 70, title: false,align:'right'},
	    	{label:'剩余数量',name: 'lastamount', index: 'lastamount', width: 70, title: false,align:'right',formatter:handle.lastAmountFmatter,},
	    	{label:'开始日期',name: 'gi_begindate', index: 'gi_begindate', width:100, title: false,align:'center'},
	    	{label:'结束日期',name: 'gi_enddate', index: 'gi_enddate', width:100, title: false,align:'center'},
	    	{label:'所需积分',name: 'gi_point', index: 'gi_point', width:80, title: false,align:'right'},
	    	{label:'商品编号',name: 'gi_pd_code', index: 'gi_pd_code', hidden:true},
	    	{label:'店铺编号',name: 'gi_shop_code', index: 'gi_shop_code', hidden:true}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			//loadonce:true, //只从后台加载一次数据，datatype被修改为local,如果弹出框想要查询则再开启为json
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-34,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			multiselect:false,//多选
			viewrecords: true,
			pgbuttons:true,
			rowNum:30,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			shrinkToFit:false,//表格是否自动填充
			autoScroll: true,
			footerrow: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id:'gi_id'
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				var ids = $("#grid").jqGrid('getDataIDs');
				var html_con = "";
				var thisclass="";
				var title="";
				var click="";
				var iconDo="";
				var state;
				var delState;
				var items=data.data.list;
				for(var i=0;i < ids.length;i++){
					if (items[i].gi_state=="上架" || items[i].gi_state=="0"){
						title="下架";
						thisclass="ui-icon-arrowthick-1-s";
						state=1;
						iconDo="&#xe60d;";
						delState=0;
						 click='onclick="javascript:handle.showGift(\''+items[i].gi_pd_code+'\',\''+items[i].gi_shop_code+'\',\''+state+'\')"';
					}else{
						title="上架";
						thisclass="ui-icon-arrowthick-1-n";
						state=0;
						iconDo="&#xe63c;";
						delState=1;
						click='onclick="javascript:handle.showGift(\''+items[i].gi_pd_code+'\',\''+items[i].gi_shop_code+'\',\''+state+'\')"';
					}
					html_con = '<div class="operating" data-id="'+ids[i]+'">';
					html_con += '<span class="iconfont i-hand '+thisclass+'" title="'+title+'" '+click+'>'+iconDo+'</span>';
					html_con += '&nbsp;<span class="iconfont i-hand ui-icon-pencil" title="修改" onclick=\"javascript:Utils.doModify(\''+items[i].gi_id+'\')\">&#xe60c;</span>';
					html_con += '&nbsp;<span class="iconfont i-hand ui-icon-image" onclick="javascript:handle.addImage(\''+items[i].gi_pd_code+'\');" title="图片上传">&#xe654;</span>';
					html_con += '&nbsp;<span title="查看流水" class="iconfont i-hand" onclick="javascript:Utils.viewgiftrun(\'' + items[i].gi_pd_code + '\',\''+items[i].gi_shop_code+'\');" >&#xe607;</span>';
					html_con += '</div>';
					var lg_pi_no_link = '<a href="javascript:void(0);" onclick="javascript:Utils.doOpenDetail('+ items[i].id+');">'+items[i].lg_pi_no+'</a>';
					$("#grid").jqGrid('setRowData',ids[i],{operate:html_con,lg_pi_no_link:lg_pi_no_link});
				}
				Public.resizeSpecifyGrid("grid",110,32);
			},
			loadError: function(xhr, status, error){		
				Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新!'});
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				Utils.doOpenDetail(rowid);
			}
	    });
	},
	buildParams:function(){
		var begindate = $("#begindate").val();//开始日期		
		var enddate = $("#enddate").val();//结束日期		
		var pd_no = $("#pd_no").val();
		var gi_state = $("#gi_state").val();
		var gi_shop_code = $("#gi_shop_code").val();
		var params = '';
		params += 'begindate='+begindate;
		params += '&enddate='+enddate;
		params += '&pd_no='+pd_no;
		params += '&gi_state='+gi_state;
		params += '&gi_shop_code='+gi_shop_code;
		return params;
	},
	reset:function(){
		$("#pd_no").val("")
		$("#gi_state_all").click();
		$("#shop_name").val("")
		$("#gi_shop_code").val("")
		$("#theDate").click();
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//重置
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			handle.operate('add');
		});
		//删除
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return;
			};
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				$.dialog.alert("您未选择任何数据");
				return;
			}
			var rowData = $("#grid").jqGrid("getRowData", rowId);
			if(rowData.gi_state == '上架'){
				Public.tips({type: 2, content : '礼品已经上架了，不允许删除!'});
				return;
			}
			if(parseInt(rowData.getamount)>0){
				Public.tips({type: 2, content : '礼品已经被领取了，不允许删除!'});
				return;
			}
			handle.del(rowId,rowData.gi_pd_code,rowData.gi_shop_code);
		});
	}
}
THISPAGE.init();

function childrenFlush(){
	THISPAGE.reloadData();
}